package nix.anim.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import nix.anim.common.pojo.NixResult;
import nix.anim.mapper.UserMapper;
import nix.anim.mapper.UserRoleMapper;
import nix.anim.pojo.User;
import nix.anim.pojo.UserExample;
import nix.anim.pojo.UserExample.Criteria;
import nix.anim.pojo.UserRole;
import nix.anim.pojo.UserRoleExample;
import nix.anim.service.UserService;

/**
 * 用户管理Service
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Value("${USER_INITIAL_PASSWORD}")
	private String USER_INITIAL_PASSWORD;
	
	@Value("${USER_SESSION_KEY}")
	private String USER_SESSION_KEY;
	
	@Value("${USER_SESSION_EXPIRE}")
	private Integer USER_SESSION_EXPIRE;
	
	@Value("${MAX_LIST_COUNT}")
	private Integer MAX_LIST_COUNT;

	@Override
	public NixResult deleteAll() {
		// 删除所有
		userMapper.deleteByExample(new UserExample());
		return NixResult.ok();
	}

	@Override
	public NixResult addUser(User user) {
		// 数据验证
		// 非空验证
		if (StringUtils.isBlank(user.getUsername())) {
			return NixResult.build(400, "用户名不能为空！");
		}
		if (StringUtils.isBlank(user.getPassword())) {
			// 设置初始密码
			user.setPassword(USER_INITIAL_PASSWORD);
		}
		// 重复验证
		UserExample userExample = new UserExample();
		Criteria criteria = userExample.createCriteria();
		criteria.andUsernameEqualTo(user.getUsername());
		List<User> userList = userMapper.selectByExample(userExample);
		if (userList != null && userList.size() > 0) {
			return NixResult.build(400, "用户名已存在！");
		}
		if (StringUtils.isNotBlank(user.getPhone())) {
			criteria = userExample.createCriteria();
			criteria.andPhoneEqualTo(user.getPhone());
			userList = userMapper.selectByExample(userExample);
			if (userList != null && userList.size() > 0) {
				return NixResult.build(400, "手机号已存在！");
			}
		}
		if (StringUtils.isNoneBlank(user.getEmail())) {
			criteria = userExample.createCriteria();
			criteria.andEmailEqualTo(user.getEmail());
			userList = userMapper.selectByExample(userExample);
			if (userList != null && userList.size() > 0) {
				return NixResult.build(400, "Email已存在！");
			}
		}
		// 密码加密
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		// 补全属性
		user.setCreated(new Date());
		user.setUpdated(new Date());
		// 添加
		userMapper.insert(user);
		return NixResult.ok(user);
	}

	@Override
	public NixResult getUserList(Integer page, Integer rows) {
		if (page == null || page <= 0) {
			page = 1;
		}
		if (rows == null || rows <= 0 || rows > MAX_LIST_COUNT) {
			rows = MAX_LIST_COUNT;
		}
		// 分页信息
		PageHelper.startPage(page, rows);
		// 执行查询
		List<User> list = userMapper.selectByExample(new UserExample());
		// 取查询结果
		PageInfo<User> pageInfo = new PageInfo<>(list);
		// 返回
		return NixResult.ok(pageInfo);
	}

	@Override
	public NixResult getUserById(Integer id) {
		if (id != null) {
			User user = userMapper.selectByPrimaryKey(id);
			if (user != null) {
				return NixResult.ok(user);
			} else {
				return NixResult.build(400, "id不存在！");
			}
		} else {
			return NixResult.build(400, "id无效！");
		}
	}

	@Override
	public NixResult updateUser(User user) {
		// 数据验证
		// id验证
		NixResult result = getUserById(user.getId());
		if (result.getStatus() != 200) {
			return result;
		}
		// 非空验证
		if (StringUtils.isBlank(user.getUsername())) {
			return NixResult.build(400, "用户名不能为空！");
		}
		// 重复验证
		UserExample userExample = new UserExample();
		Criteria criteria = userExample.createCriteria();
		criteria.andUsernameEqualTo(user.getUsername());
		criteria.andIdNotEqualTo(user.getId());
		List<User> userList = userMapper.selectByExample(userExample);
		if (userList != null && userList.size() > 0) {
			return NixResult.build(400, "用户名已存在！");
		}
		if (StringUtils.isNotBlank(user.getPhone())) {
			criteria = userExample.createCriteria();
			criteria.andPhoneEqualTo(user.getPhone());
			criteria.andIdNotEqualTo(user.getId());
			userList = userMapper.selectByExample(userExample);
			if (userList != null && userList.size() > 0) {
				return NixResult.build(400, "手机号已存在！");
			}
		}
		if (StringUtils.isNoneBlank(user.getEmail())) {
			criteria = userExample.createCriteria();
			criteria.andEmailEqualTo(user.getEmail());
			criteria.andIdNotEqualTo(user.getId());
			userList = userMapper.selectByExample(userExample);
			if (userList != null && userList.size() > 0) {
				return NixResult.build(400, "Email已存在！");
			}
		}
		// 更新属性
		user.setUpdated(new Date());
		// 更新
		userMapper.updateByPrimaryKeySelective(user);
		return NixResult.ok();
	}

	@Override
	public NixResult resetPassword(Integer id) {
		// id验证
		NixResult result = getUserById(id);
		if (result.getStatus() != 200) {
			return result;
		}
		// 组装pojo（Selective）
		User user = new User();
		user.setId(id);
		// 密码加密
		user.setPassword(DigestUtils.md5DigestAsHex(USER_INITIAL_PASSWORD.getBytes()));
		user.setUpdated(new Date());
		// 更新
		userMapper.updateByPrimaryKeySelective(user);
		return NixResult.ok();
	}

	@Override
	public NixResult getUserRoleIds(Integer id) {
		// id验证
		NixResult result = getUserById(id);
		if (result.getStatus() != 200) {
			return result;
		}
		// 条件查询
		UserRoleExample example = new UserRoleExample();
		nix.anim.pojo.UserRoleExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(id);
		List<UserRole> list = userRoleMapper.selectByExample(example);
		// 转为数组
		Integer[] ids = new Integer[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ids[i] = list.get(i).getRoleId();
		}
		return NixResult.ok(ids);
	}

	@Override
	public NixResult setUserRole(Integer userId, String roleIds) {
		// id验证
		NixResult result = getUserById(userId);
		if (result.getStatus() != 200) {
			return result;
		}
		// 删除现有角色
		UserRoleExample example = new UserRoleExample();
		nix.anim.pojo.UserRoleExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId);
		userRoleMapper.deleteByExample(example);
		// 遍历插入新角色
		String[] ids = roleIds.split(",");
		for (String roleId : ids) {
			UserRole userRole = new UserRole();
			userRole.setUserId(userId);
			userRole.setRoleId(Integer.parseInt(roleId));
			userRole.setCreated(new Date());
			userRole.setUpdated(new Date());
			userRoleMapper.insert(userRole);
		}
		return NixResult.ok();
	}

}
